var dataUrl = null;
var pageii = null;
var projectId = 0;
var reportType = 0;
$(function () {
    init();
    $("#generateReport").click(function () {
        generateReport();
    });
    $("#reportType").change(function () {
        reportType = this.value
        if (this.value == "") {
            $("#corpDiv").hide()
        } else {
            if (this.value == 1) {
                $("#corpDiv").hide()
                findReportVersion();
            } else {
                $("#corpDiv").show()
                findReportVersion();
            }
        }
    })

});

function init() {
    // dataUrl = $("#dataUrl").val();
    dataUrl = "/modules";
    getProjectName();
    getReportCategory();
    // findReportVersion();
}

/**
 * 获取项目名称
 * @param cropId
 */
function getProjectName() {
    var index = layer.load(1, {shade: false});
    var url = dataUrl + "/homepage/allProjectByPersonIdAndCorpId?personId=" + $("#personId").val() + "&newDate=" + (new Date().getTime());
    ;
    $.ajax({
        url: url,
        method: "get",
        dataType: "json",
        success: function (result) {
            var html = "";
            html += "<option value=''>------请选择------</option>";
            if (result != null) {
                for (var i = 0; i < result.length; i++) {
                    html += "<option value='" + result[i].id + "'>" + (result[i].caption) + "</option>";
                }
                $("#projectName").html(html);
                $('#projectName').searchableSelect({
                    afterSelectItem: function () {
                        projectId = this.holder.data("value")

                        getCorpList()
                        if (reportType == '1') {
                            findReportVersion()
                        }
                    }
                });
            } else {
                layer.msg("获取列表信息错误，请联系管理员！");
            }
            layer.close(index);
        }

    });
}

/**
 * 获取单位名称
 * @param cropId
 */
function getCorpList() {
    if (projectId != "" && projectId != 0) {
        var url = dataUrl + "/projectManage/getCorpListByProjectId?projectId=" + projectId + "&newDate=" + (new Date().getTime());
        $.ajax({
            url: url,
            method: "get",
            dataType: "json",
            success: function (result) {
                var html = "";
                html += "<option value=''>------请选择------</option>";
                if (result != null) {
                    for (var i = 0; i < result.length; i++) {
                        html += "<option value='" + result[i].id + "'>" + (result[i].caption) + "</option>";
                    }
                    $("#corp").html(html);
                } else {
                    layer.msg("获取列表信息错误，请联系管理员！");
                }
            }
        });
    } else {
        var html = "";
        html += "<option value=''>------请选择------</option>";
        $("#corp").html(html);
    }

    // findReportVersion();
}

/**
 * 获取报表类型
 * @param cropId
 */
function getReportCategory() {
    var url = dataUrl + "/basicReport/findReportCategory?type=2&newDate=" + (new Date().getTime());
    $.ajax({
        url: url,
        method: "get",
        dataType: "json",
        success: function (result) {
            var html = "";
            html += "<option value=''>----请选择----</option>";
            if (result != null) {
                for (var i = 0; i < result.length; i++) {
                    html += "<option value='" + result[i].subType + "'>" + (result[i].subCaption) + "</option>";
                }
                $("#reportType").html(html);
            } else {
                layer.msg("获取列表信息错误，请联系管理员！");
            }
        }
    });
}

function findReportVersion() {
    var url = dataUrl + "/basicReport/findReportVersion?type=2&newDate=" + (new Date().getTime());
    // $("#propName").find("option:selected").attr("data-id");
    // var projectId = $("#projectName").val();
    if (projectId != null && projectId != "" && projectId != undefined) {
        url += "&&projectId=" + projectId;
    } else {
        // layer.msg("请选择单位！");
        return;
    }
    var reportType = $("#reportType").val();
    if (reportType != null && reportType != "" && reportType != undefined) {
        url += "&&subType=" + reportType;
    }
    if (reportType != '1') {
        var corpId = $("#corp").val();
        if (corpId != null && corpId != "" && corpId != undefined) {
            url += "&&corpId=" + corpId;
        } else {
            // layer.msg("请选择单位！");
            return;
        }
    }
    $.ajax({
        url: url,
        method: "get",
        dataType: "json",
        success: function (result) {
            var html = "";
            if (result != null) {
                $("#dataTable").show();
                if (result.length > 0) {
                    // $("#generateReport").hide();
                    for (var i = 0; i < result.length; i++) {
                        html += "  <tr role=\"row\" class=\"odd\">" +
                            "  <th width=\"75px\"><a onclick=\"reportLook('" + result[i].url + "')\">" + result[i].caption + "</a>\n" +
                            "            </th>" +
                            "            <th width=\"150px\">" + crtTimeFtt(result[i].time) + "</th>" +
                            "            <th width=\"150px\">" +
                            "<a class='dropdown-toggle' style='color: #197eb8'  href='javascript:download(\""+result[i].url+"\")'>下载</a>&nbsp;&nbsp;&nbsp;"+
                            "<a class='dropdown-toggle'  " +
                            "href='javascript:findReportVersionLine()'>折线图</a>"

                            + "&nbsp;&nbsp;&nbsp;<a class='dropdown-toggle' style='color: red' " +
                            "href='javascript:deleteVersion(\"" + result[i].id + "\")'>删除</a>" +
                            "</th>" +

                            "        </tr>";
                    }
                } else {
                    // $("#dataTable").hide();
                    // $("#generateReport").show();
                }

                $("#reportVersion").html(html);
            } else {
                layer.msg("获取列表信息错误，请联系管理员！");

            }
        }
    });
}

function deleteVersion(id) {
    var url = "/reportManage/deleteReportVersion?id=" + id + "&newDate=" + (new Date().getTime());
    $.ajax({
        url: url,
        method: "get",
        dataType: "text",
        success: function (result) {
            if (result != null) {
                layer.msg("删除成功")
                findReportVersion()
            } else {
                layer.msg("删除失败！");

            }
        }
    });

}

/**
 * 生成报表
 */
function generateReport() {
    var url = dataUrl + "/basicReport/generateReport?type=2&newDate=" + (new Date().getTime());
    // var projectId = $("#projectName").val();

    var reportType = $("#reportType").val();
    if (reportType != null && reportType != "" && reportType != undefined) {
        url += "&&subType=" + reportType;
    } else {
        layer.msg("请选择表名");
        return;
    }
    if (projectId != null && projectId != "" && projectId != undefined && projectId != 0) {
        url += "&&projectId=" + projectId;
    } else {
        layer.msg("请选择项目！");
        return;
    }

    if (reportType != '1') {
        var corpId = $("#corp").val();
        if (corpId != null && corpId != "" && corpId != undefined) {
            url += "&&corpId=" + corpId;
        } else {
            layer.msg("请选择单位！");
            return;
        }
    }
    $.ajax({
        url: url,
        method: "get",
        dataType: "text",
        success: function (result) {
            if (result == 'success') {
                layer.msg("生成成功");
                findReportVersion();
            } else {
                findReportVersion();
                // layer.msg("生成失败");
            }
        }
    });
}

/**
 * 预览
 * @param url
 */
function reportLook(url) {
    window.open("https://view.officeapps.live.com/op/view.aspx?src=" + url);
}

function findReportVersionLine() {


    var url = dataUrl + "/detailedReport/detailedReport";
    var params = {};
    params.newDate = new Date().getTime()
    // params.projectId = projectId
    if (projectId != null && projectId != "" && projectId != undefined && projectId != 0) {
        params.projectId = projectId
    } else {
        return;
    }
    if (reportType != null && reportType != "" && reportType != undefined && reportType != 0) {
        params.reportType = reportType
    } else {
        return;
    }
    if (reportType != 1 && reportType != 0 && reportType != "") {
        var corpId = $("#corp").val();
        if (corpId != null && corpId != "" && corpId != undefined) {
            params.corpId = corpId
        } else {
            return;
        }
        url = dataUrl + "/detailedReport/detailedCorpPersonReport";
        // ryTj(url,params)
    } else {
    }
    dwTj(url, params)


    pageii = layer.open({
        title: "折线图",
        type: 1,
        fixed: true,
        //shadeClose : true,
        area: ["95%", "60%"],
        content: $("#supervise-charts")
    })
}

function dwTj(url, params) {
    var trendsChart = echarts.init(document.getElementById('supervise-charts'))
    $.ajax({
        // url: '../../../statics/json/homepage.json',
        type: "POST",
        url: url,
        dataType: "json",
        data: params,
        success: function (resultData) {
            // res = JSON.parse(res)
            var xList = []
            var seriesData = []
            var res = resultData.list


            for (var i = 0; i < resultData.xList.length; i++) {
                xList.push(resultData.xList[i])
            }
            for (var i = 0; i < res.length; i++) {
                var data = [];
                /* if(res[i].key!='浙江启明电力集团有限公司'){
                     continue
                 }*/

                for (var j = 0; j < res[i].list.length; j++) {
                    var date = new Date(res[i].list[j].Start_Time);
                    // if (dateType == 4) {
                    //     date = res[i].list[j].createTime;
                    // }
                    // date = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();

                    var value = {
                        name: res[i].key,
                        // value: [date, res[i].list[j].price, res[i].list[j].Corp_Caption]
                        value: [res[i].list[j].timeNum, res[i].list[j].price, res[i].list[j].Caption]
                    }

                    data.push(value)
                }
                var series = {
                    name: res[i].key,
                    type: 'line',
                    // showSymbol: false,
                    // hoverAnimation: false,
                    data: data
                }

                seriesData.push(series)

                // xData.push(res.rows[i].key.slice(5))
            }

            trendsChart.setOption({
                legend: {},

                tooltip: {
                    trigger: 'axis',
                    formatter: function (data) {
                        params = data[0];
                        // console.log(data)
                        // console.log(params)
                        // console.log(index)
                        // var date = new Date(params.value[0]);

                        return params.name + "<br/>"
                            // +params.value[2] + "<br/>"
                            // + (date.getMonth() + 1) + '月' + date.getDate() + '日,' +
                            + '得分' + params.value[1];

                    },
                    axisPointer: {
                        animation: false
                    }
                },
                xAxis: {
                    type: "value",
                    minInterval: 1,
                    // boundaryGap: false,
                    data: xList
                },
                /*  xAxis: {
                      type: 'time' ,
                      minInterval: 1,
                       splitLine: {
                            show: false
                        },
                        axisLabel: {
                            show: true,
                            interval : 1,
                            // 使用函数模板，函数参数分别为刻度数值（类目），刻度的索引
                            formatter: function (value, index) {
                                // 格式化成月/日，只在第一个刻度显示年份
                                // var date = new Date(value);
                                // var texts = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日";
                                // return texts;
                                return index+1;
                            }
                        }
                  },*/
                yAxis: {
                    type: 'value',
                    boundaryGap: [0, '100%'],
                    splitLine: {
                        show: false
                    }
                },
                series: seriesData
            }, true);
        }
    })
}

function ryTj(url, params) {
    var trendsChart = echarts.init(document.getElementById('supervise-charts'))
    $.ajax({
        // url: '../../../statics/json/homepage.json',
        type: "POST",
        url: url,
        dataType: "json",
        data: params,
        success: function (res) {
            // res = JSON.parse(res)
            // var xList=[]
            var seriesData = []
            // var res =resultData.list


            // for (var i = 0; i < resultData.xList.length; i++) {
            //     xList.push( resultData.xList[i])
            // }
            for (var i = 0; i < res.length; i++) {
                var data = [];
                /* if(res[i].key!='浙江启明电力集团有限公司'){
                     continue
                 }*/

                for (var j = 0; j < res[i].list.length; j++) {
                    var date = new Date(res[i].list[j].Start_Time);
                    // if (dateType == 4) {
                    //     date = res[i].list[j].createTime;
                    // }
                    // date = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();

                    var value = {
                        name: res[i].key,
                        value: [date, res[i].list[j].price, res[i].list[j].Corp_Caption]
                        // value: [res[i].list[j].timeNum, res[i].list[j].price, res[i].list[j].Caption]
                    }

                    data.push(value)
                }
                var series = {
                    name: res[i].key,
                    type: 'line',
                    // showSymbol: false,
                    // hoverAnimation: false,
                    data: data
                }

                seriesData.push(series)

                // xData.push(res.rows[i].key.slice(5))
            }

            trendsChart.setOption({
                legend: {},

                tooltip: {
                    trigger: 'axis',
                    formatter: function (data) {
                        params = data[0];
                        // console.log(data)
                        // console.log(params)
                        // console.log(index)
                        // var date = new Date(params.value[0]);

                        return params.name + "<br/>"
                            // +params.value[2] + "<br/>"
                            // + (date.getMonth() + 1) + '月' + date.getDate() + '日,' +
                            + '得分' + params.value[1];

                    },
                    axisPointer: {
                        animation: false
                    }
                },
                /*  xAxis: {
                      type:"value" ,
                      // boundaryGap: false,
                      data: xList
                  },*/
                xAxis: {
                    type: 'time',
                    minInterval: 1,
                    splitLine: {
                        show: false
                    },
                    axisLabel: {
                        show: true,
                        interval: 1,
                        // 使用函数模板，函数参数分别为刻度数值（类目），刻度的索引
                        formatter: function (value, index) {
                            // 格式化成月/日，只在第一个刻度显示年份
                            // var date = new Date(value);
                            // var texts = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日";
                            // return texts;
                            return index + 1;
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    boundaryGap: [0, '100%'],
                    splitLine: {
                        show: false
                    }
                },
                series: seriesData
            }, true);
        }
    })
}

/**
 * 下载
 * @param url
 */
function download(url) {
    window.open( url);
}

//创建时间格式化显示
function crtTimeFtt(value, row, index) {
    var crtTime = new Date(value);
    return dateFtt("yyyy-MM-dd hh:mm:ss", crtTime);//直接调用公共JS里面的时间类处理的办法
}

/**************************************时间格式化处理************************************/
function dateFtt(fmt, date) { //author: meizz
    var o = {
        "M+": date.getMonth() + 1,                 //月份
        "d+": date.getDate(),                    //日
        "h+": date.getHours(),                   //小时
        "m+": date.getMinutes(),                 //分
        "s+": date.getSeconds(),                 //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}